﻿var TestResult = function(){};
TestResult.prototype = {
	must: undefined,
	actual: undefined,
	title: undefined
};

var TestSiute = function (aArray)
{
	if (aArray instanceof Array) {
		//this = this.concat(aArray);
		for (var x = 0; x < aArray.length; x++) {
			this.push(aArray[x]);
		}
	}
};
TestSiute.prototype = new Array();
TestSiute.prototype.startTests = function (oTested)
{
	var aResults = [];
	for (var i = 0; i < this.length; i++) {
		aResults.push(this.DOMResultGenerate(this[i], oTested));
	};
	return aResults;
};
TestSiute.prototype.concat = function (oTestSiute)
{
	if (oTestSiute === undefined) {
		return this;
	}

	if (!(oTestSiute instanceof Array)) {
		oTestSiute = new Array(oTestSiute);
	}

	for (var x = 0; x < oTestSiute.length; x++) {
		this.push(oTestSiute[x]);
	}
	return this;
}
TestSiute.prototype.DOMResultGenerate = function (fResult, oTested)
{
	var oResult;
	try {
		oResult = fResult(oTested);
	} catch (error) {
		oResult = new TestResult();
		oResult.title = 'Test <b>' + fResult.name + '</b> have error (' + error.toString() + ')';
		oResult.actual = undefined;
		oResult.must = null;
	}

	var domLi = document.createElement('li');
	var isEqual = function (must, actual)
	{
		if (must instanceof Array) {
			bResult = true;
			if (must.length !== actual.length) { return false; }
			for (var i = 0; i < must.length; i++) {
				if (!isEqual(must[i], actual[i])) {
					return false;
				}
			}
			return true;
		}

		if (must instanceof Object) {
			for (var x in must) {
				if (!must.hasOwnProperty(x)) {
					return false;
				}
				if ((actual[x] === undefined) || !isEqual(must[x], actual[x])) {
					return false
				}
			}
			return true;
		}

		return must === actual;
	};
	domLi.innerHTML = oResult.title + ' : ' + (isEqual(oResult.must, oResult.actual) ? '<span class="success"></span>' : '<span class="fail"></span>');
	return domLi;
}

/**
 * @param {TestSiute} aTests
 */
function TestEngine(oTested, TestSiute, domResultPlace)
{
	if (!domResultPlace) {
		domResultPlace = document.body;
	}
	domResultPlace.className = 'jsunit';
	
	var domList = document.createElement('ul');
	domList.style.listStyleType = 'decimal';

	var aResults = TestSiute.startTests(oTested);
	for (var i = 0; i < aResults.length; i++) {
		domList.appendChild(aResults[i]);
	}
	domResultPlace.appendChild(domList);
}